package itsm.isperp.framework.ldap.synchronize;

import itsm.isperp.framework.ldap.LdapContextUtils;

import java.util.ArrayList;
import java.util.List;

import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.LdapContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * ad域组织机构同步数据
 * 
 * 
 * @author lizx
 * @date 2014-9-7
 * @since 1.0
 * 
 */
public class UnitSync {

	protected final static Log logger = LogFactory.getLog(UnitSync.class);

	/**
	 * 获取ad的组织列表
	 * 
	 * @return
	 * @throws NamingException
	 */
	public static List<String[]> readData(String dc, String systemUserOU,
			LdapContext ctx) throws NamingException {
		List<String[]> list = new ArrayList<>();

		// 获取同步到系统的组织机构
		String searchBase = LdapContextUtils.getDomainControllerOU(dc,
				systemUserOU);

		String searchFilter = LdapContextUtils.UNIT;

		// 搜索控制器
		SearchControls searchCtls = new SearchControls();
		// 创建搜索控制器
		searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
		String returnedAtts[] = { "name", "distinguishedName" };
		searchCtls.setReturningAttributes(returnedAtts); // 设置返回属性集
		NamingEnumeration<SearchResult> answer = ctx.search(searchBase,
				searchFilter, searchCtls);

		while (answer.hasMoreElements()) {// 遍历结果集
			SearchResult sr = (SearchResult) answer.next();
			String dn = sr.getName();
			logger.info("ad->dn：" + dn);
			Attributes attrs = sr.getAttributes();
			if (attrs != null) {
				Attribute attr = attrs.get("distinguishedName");
				Attribute attrName = attrs.get("name");

				String ou = (String) attr.get();
				String unitName = (String) attrName.get();

				logger.info("ad->distinguishedName：" + ou);
				logger.info("ad->name：" + unitName);

				String unitPath = getUnitPath(ou);

				String[] r = new String[3];
				r[0] = unitName;
				r[1] = unitPath.replace(unitName + "/", "");
				r[2] = unitPath;
				list.add(r);

			}
		}

		return list;
	}

	public static String getUnitPath(String ou) {
		String unitPath = "/";
		if (ou != null) {
			String[] ouArr = ou.split(",");
			int ouLen = ouArr.length - 1;
			for (int i = ouLen; i >= 0; i--) {
				String s = ouArr[i];
				if (s.contains("OU")) {
					unitPath = unitPath + s.split("=")[1] + "/";
				}
			}

		}
		return unitPath;
	}
}
